import { isFunction } from '@/utils'

interface DeleteOptions {
  visible: boolean
  title: string
  message: string
}
interface UseDeleteOptions {
  subject?: string
  msgKey?: string
  paramsFn?: Function
  apikey: string
  onDeleted?: Function
}
export function useDelete({
  subject = '',
  msgKey = 'name',
  paramsFn = row => ({ uuid: row.uuid }),
  apikey,
  onDeleted = null, // 删除成功后的回调
}: UseDeleteOptions) {
  const loading = useLoading()
  const currentRow = ref<any>({})

  const deleteOptions: DeleteOptions = reactive({
    visible: false,
    title: `删除${subject}`,
    message: `确定删除该${subject}吗？`,
  })

  function openDelete(row) {
    currentRow.value = row
    const msg = currentRow.value[msgKey] || ''
    deleteOptions.message = `确定删除 ${subject} <b> ${msg}</b> ？`
    deleteOptions.visible = true
  }
  async function deleteDone() {
    loading.open()
    if (!apikey)
      return
    let params = {}
    if (paramsFn && isFunction(paramsFn))
      params = paramsFn(currentRow.value)
    // else
    //   params = Object.fromEntries(paramsFn.map(key => [key, currentRow.value[key]]))

    const result = await useRequest(apikey, params) as any
    loading.close()
    deleteOptions.visible = false
    if (result.success) {
      ElNotification({
        type: 'success',
        message: `${subject}删除成功`,
      })
      onDeleted()
    }
    else {
      ElNotification({
        type: 'error',
        message: `${subject}删除失败`,
      })
    }
  }
  return {
    deleteOptions,
    openDelete,
    deleteDone,
  }
}
